package com.gxuwz.bignews.fragments;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.gxuwz.bignews.R;
import com.gxuwz.bignews.controller.ResetPasswordController;
import com.gxuwz.bignews.model.util.NotificationUtil;

import java.util.Random;

public class ResetPasswordFragment extends Fragment {
    // UI元素
    private RadioGroup rgResetMethod;
    private RadioButton rbMethodPassword, rbMethodPhone;
    private LinearLayout layoutPasswordMethod, layoutPhoneMethod;
    private LinearLayout layoutStep1, layoutStep2, layoutStep3;
    private EditText etOldPassword, etNewPasswordByOld, etConfirmPasswordByOld;
    private EditText etPhoneReset, etVerificationCode, etNewPasswordByPhone, etConfirmPasswordByPhone;
    private Button btnResetByOldPassword, btnGetVerificationCode, btnVerifyCode, btnResetByPhone;
    private ImageButton btnBack;
    
    // 业务逻辑控制器
    private ResetPasswordController resetPasswordController;
    
    // 验证码
    private String verificationCode;
    
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.user_reset_password, container, false);
        
        // 隐藏底部导航栏
        if (getActivity() != null) {
            View nav = getActivity().findViewById(R.id.nav_view);
            if (nav != null) nav.setVisibility(View.GONE);
        }
        
        resetPasswordController = new ResetPasswordController(getContext());
        
        // 初始化视图
        initViews(view);
        // 设置初始状态
        setupInitialState();
        // 设置事件监听器
        setupListeners();
        
        return view;
    }
    
    // 生成6位随机验证码
    private String generateRandomCode() {
        Random random = new Random();
        int code = 100000 + random.nextInt(900000); // 生成100000-999999之间的随机数
        return String.valueOf(code);
    }
    
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        // 恢复底部导航栏
        if (getActivity() != null) {
            View nav = getActivity().findViewById(R.id.nav_view);
            if (nav != null) nav.setVisibility(View.VISIBLE);
        }
    }
    
    private void initViews(View view) {
        // 切换方式
        rgResetMethod = view.findViewById(R.id.reset_method_group);
        rbMethodPassword = view.findViewById(R.id.rb_method_password);
        rbMethodPhone = view.findViewById(R.id.rb_method_phone);
        
        // 两种方法的布局
        layoutPasswordMethod = view.findViewById(R.id.layout_password_method);
        layoutPhoneMethod = view.findViewById(R.id.layout_phone_method);
        
        // 方法1: 通过原密码修改
        etOldPassword = view.findViewById(R.id.et_old_password);
        etNewPasswordByOld = view.findViewById(R.id.et_new_password_by_old);
        etConfirmPasswordByOld = view.findViewById(R.id.et_confirm_password_by_old);
        btnResetByOldPassword = view.findViewById(R.id.btn_reset_by_old_password);
        
        // 方法2: 通过手机验证修改
        layoutStep1 = view.findViewById(R.id.layout_step_1);
        layoutStep2 = view.findViewById(R.id.layout_step_2);
        layoutStep3 = view.findViewById(R.id.layout_step_3);
        
        etPhoneReset = view.findViewById(R.id.et_phone_reset);
        etVerificationCode = view.findViewById(R.id.et_verification_code);
        etNewPasswordByPhone = view.findViewById(R.id.et_new_password_by_phone);
        etConfirmPasswordByPhone = view.findViewById(R.id.et_confirm_password_by_phone);
        
        btnGetVerificationCode = view.findViewById(R.id.btn_get_verification_code);
        btnVerifyCode = view.findViewById(R.id.btn_verify_code);
        btnResetByPhone = view.findViewById(R.id.btn_reset_by_phone);
        
        // 返回按钮
        btnBack = (ImageButton) view.findViewById(R.id.btn_back);
        
        // 预填充当前登录用户的手机号
        String currentPhone = resetPasswordController.getCurrentUserPhone();
        etPhoneReset.setText(currentPhone);
    }
    
    private void setupInitialState() {
        // 默认显示原密码重置方法
        layoutPasswordMethod.setVisibility(View.VISIBLE);
        layoutPhoneMethod.setVisibility(View.GONE);
        
        // 手机验证方式默认显示第一步
        layoutStep1.setVisibility(View.VISIBLE);
        layoutStep2.setVisibility(View.GONE);
        layoutStep3.setVisibility(View.GONE);
    }
    
    private void setupListeners() {
        // 切换重置密码方式
        rgResetMethod.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.rb_method_password) {
                    layoutPasswordMethod.setVisibility(View.VISIBLE);
                    layoutPhoneMethod.setVisibility(View.GONE);
                } else if (checkedId == R.id.rb_method_phone) {
                    layoutPasswordMethod.setVisibility(View.GONE);
                    layoutPhoneMethod.setVisibility(View.VISIBLE);
                    // 重置手机验证方式的步骤
                    layoutStep1.setVisibility(View.VISIBLE);
                    layoutStep2.setVisibility(View.GONE);
                    layoutStep3.setVisibility(View.GONE);
                }
            }
        });
        
        // 1. 原密码修改方式
        btnResetByOldPassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                resetByOldPassword();
            }
        });
        
        // 2. 手机验证修改方式
        btnGetVerificationCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getVerificationCode();
            }
        });
        
        btnVerifyCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                verifyCode();
            }
        });
        
        btnResetByPhone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                resetByPhone();
            }
        });
        
        // 返回按钮
        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (getActivity() != null) {
                    getActivity().getSupportFragmentManager().popBackStack();
                }
            }
        });
    }
    
    // 方法1：通过原密码修改密码
    private void resetByOldPassword() {
        String oldPassword = etOldPassword.getText().toString().trim();
        String newPassword = etNewPasswordByOld.getText().toString().trim();
        String confirmPassword = etConfirmPasswordByOld.getText().toString().trim();
        String currentPhone = resetPasswordController.getCurrentUserPhone();
        
        // 检查输入是否为空
        if (oldPassword.isEmpty() || newPassword.isEmpty() || confirmPassword.isEmpty()) {
            Toast.makeText(getContext(), "请填写完整信息", Toast.LENGTH_SHORT).show();
            return;
        }
        
        // 检查两次输入的新密码是否一致
        if (!newPassword.equals(confirmPassword)) {
            Toast.makeText(getContext(), "两次输入的新密码不一致", Toast.LENGTH_SHORT).show();
            return;
        }
        
        // 验证原密码是否正确
        if (resetPasswordController.verifyOldPassword(currentPhone, oldPassword)) {
            // 更新密码
            boolean result = resetPasswordController.resetPassword(currentPhone, newPassword);
            if (result) {
                Toast.makeText(getContext(), "密码修改成功", Toast.LENGTH_SHORT).show();
                // 返回个人中心
                if (getActivity() != null) {
                    getActivity().getSupportFragmentManager().popBackStack();
                }
            } else {
                Toast.makeText(getContext(), "密码修改失败", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(getContext(), "原密码不正确", Toast.LENGTH_SHORT).show();
        }
    }
    
    // 方法2-1：获取验证码
    private void getVerificationCode() {
        String phone = etPhoneReset.getText().toString().trim();
        
        if (phone.isEmpty()) {
            Toast.makeText(getContext(), "请输入手机号", Toast.LENGTH_SHORT).show();
            return;
        }
        
        // 检查手机号是否存在
        if (resetPasswordController.isPhoneRegistered(phone)) {
            // 生成随机6位验证码
            verificationCode = generateRandomCode();
            
            // 显示通知栏验证码
            if (getContext() != null) {
                NotificationUtil.showVerificationCodeNotification(getContext(), verificationCode);
                Toast.makeText(getContext(), "验证码已发送到通知栏", Toast.LENGTH_SHORT).show();
            }
            
            // 显示下一步
            layoutStep1.setVisibility(View.GONE);
            layoutStep2.setVisibility(View.VISIBLE);
        } else {
            Toast.makeText(getContext(), "该手机号未注册", Toast.LENGTH_SHORT).show();
        }
    }
    
    // 方法2-2：验证验证码
    private void verifyCode() {
        String code = etVerificationCode.getText().toString().trim();
        
        if (code.isEmpty()) {
            Toast.makeText(getContext(), "请输入验证码", Toast.LENGTH_SHORT).show();
            return;
        }
        
        // 验证验证码
        if (code.equals(verificationCode)) {
            Toast.makeText(getContext(), "验证码正确", Toast.LENGTH_SHORT).show();
            
            // 显示下一步
            layoutStep2.setVisibility(View.GONE);
            layoutStep3.setVisibility(View.VISIBLE);
        } else {
            Toast.makeText(getContext(), "验证码错误", Toast.LENGTH_SHORT).show();
        }
    }
    
    // 方法2-3：通过手机验证重置密码
    private void resetByPhone() {
        String newPassword = etNewPasswordByPhone.getText().toString().trim();
        String confirmPassword = etConfirmPasswordByPhone.getText().toString().trim();
        String phone = etPhoneReset.getText().toString().trim();
        
        if (newPassword.isEmpty() || confirmPassword.isEmpty()) {
            Toast.makeText(getContext(), "请填写完整信息", Toast.LENGTH_SHORT).show();
            return;
        }
        
        if (!newPassword.equals(confirmPassword)) {
            Toast.makeText(getContext(), "两次输入的密码不一致", Toast.LENGTH_SHORT).show();
            return;
        }
        
        // 更新密码
        boolean result = resetPasswordController.resetPassword(phone, newPassword);
        if (result) {
            Toast.makeText(getContext(), "密码重置成功", Toast.LENGTH_SHORT).show();
            // 返回个人中心
            if (getActivity() != null) {
                getActivity().getSupportFragmentManager().popBackStack();
            }
        } else {
            Toast.makeText(getContext(), "密码重置失败", Toast.LENGTH_SHORT).show();
        }
    }
} 